package com.beijing.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author Ma Wenqi
 * @Date 2021/3/29 15:22
 * @Version 1.0
 */
//动态创建对象，通过反射
public class Demo08 {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        //获得class对象
        Class c1 = Class.forName("com.beijing.reflection.User");
        //创建一个对象
        System.out.println("============================");
        User user = (User)c1.newInstance();//本质是调用了类的无参构造器
        System.out.println(user);
        //通过构造器创建对象
        System.out.println("============================");
        Constructor constructor = c1.getDeclaredConstructor(String.class,int.class);
        User user2 = (User)constructor.newInstance("打爆",22);
        System.out.println(user2);
        //通过反射调用普通方法
        //通过反射获取一个方法
        System.out.println("============================");
        Method setName = c1.getDeclaredMethod("setName",String.class);
        //invoke:激活的意思
        //参数：对象，方法的值
        setName.invoke(user,"韩威");
        System.out.println(user.getName());
        System.out.println("============================");
        //通过反射操作属性
        User user3 = (User)c1.newInstance();
        Field name = c1.getDeclaredField("name");
        //不能直接操作私有属性，我们需要关闭程序的安全监测，属性或方法的setAccessible(true)
        name.setAccessible(true);
        name.set(user3,"小宝");
        System.out.println(user3.getName());
    }
}

